﻿using EnduroUserDataSample.Common;

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

using Windows.Storage;
using System.Threading.Tasks;
using OrandoLabs.Common;
using OrandoLabs.EnduroStore;

// The Grid App template is documented at http://go.microsoft.com/fwlink/?LinkId=234226

namespace EnduroUserDataSample
{
    /// <summary>
    /// Provides application-specific behavior to supplement the default Application class.
    /// </summary>
    sealed partial class App : Application
    {
        EnduroObjectStore Store;
        EnduroDatabase Database;
        OrandoInstance Instance;
        EnduroInstance EInstance;
        Exception EnduroException;
        EnduroStoreDatabase StoreDatabase;
        String EnduroDirName = "enduro-dir";
        String EnduroInstanceName = "enduro";
        String EnduroDatabaseName = "enduro.edb";

        PrefsObject Prefs;
        UserObject CurrentUser;

        private async Task<bool> InitializeEnduroAsync()
        {
            EnduroException = null;
            var appData = Windows.Storage.ApplicationData.Current;
            var path = appData.LocalFolder.CreateFolderAsync(EnduroDirName, CreationCollisionOption.OpenIfExists);
            var folder = await path.AsTask<Windows.Storage.StorageFolder>();
            var baseDir = folder.Path;

            return await Task.Run(() =>
            {
                bool inner = true;
                try
                {
                    Instance = new OrandoInstance(EnduroInstanceName, baseDir);
                    EInstance = new EnduroInstance(Instance);
                    Database = new EnduroDatabase(EInstance, EnduroDatabaseName);
                    StoreDatabase = new EnduroStoreDatabase("enduro", Database);
                }
                catch (Exception e)
                {
                    inner = false;
                    EnduroException = e;
                }
                return inner;
            }
            );
        }

        private async Task<bool> DefineEnduroObjectStore()
        {
            Store = new EnduroObjectStore(StoreDatabase, "myp", "http://my.namespace.com");
            Store.DeclareObject<UserObject>();
            Store.DeclareObject<PrefsObject>();
            Store.DeclareObject<LinkObject>();
            return await Store.DefineModelAsync();
        }

        private async Task<UserObject> QueryEnduroObjectStore(String email)
        {
            UserObject auser = await Store.FetchObjectFromIdAsync<UserObject>(email);
            if (auser != null) return auser;
            // Add a new user
            auser = Store.NewObject<UserObject>(email);
            auser.Email = email;

            PrefsObject prefs = Store.NewObject<PrefsObject>();
            prefs.Age = 1;
            prefs.Language = "English";
            prefs.Birthday = new DateTime(2013, 4, 11);

            auser.Prefs = prefs;

            LinkObject link1 = Store.NewObject<LinkObject>();
            link1.Url = "http://www.orandolabs.com";
            link1.Title = "Orando Labs";
            LinkObject link2 = Store.NewObject<LinkObject>();
            link2.Url = "http://orandolabs.codeplex.com";
            link2.Title = "Orando Labs Development";

            auser.AddLink(link1);
            auser.AddLink(link2);

            String triples = Store.GetWALAsString();
            await Store.FlushAsync(false);
            return auser;
        }

        private async Task<bool> TerminateEnduroAsync()
        {
            return await Task.Run(() =>
            {
                if (Instance != null)
                {
                    Instance.Dispose();
                    Instance = null;
                }
                return true;
            }
            );
        }

        /// <summary>
        /// Initializes the singleton Application object.  This is the first line of authored code
        /// executed, and as such is the logical equivalent of main() or WinMain().
        /// </summary>
        public App()
        {
            this.InitializeComponent();
            this.Suspending += OnSuspending;
        }

        /// <summary>
        /// Invoked when the application is launched normally by the end user.  Other entry points
        /// will be used when the application is launched to open a specific file, to display
        /// search results, and so forth.
        /// </summary>
        /// <param name="args">Details about the launch request and process.</param>
        protected override async void OnLaunched(LaunchActivatedEventArgs args)
        {
            Frame rootFrame = Window.Current.Content as Frame;

            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active
            
            if (rootFrame == null)
            {
                // Create a Frame to act as the navigation context and navigate to the first page
                rootFrame = new Frame();
                //Associate the frame with a SuspensionManager key                                
                SuspensionManager.RegisterFrame(rootFrame, "AppFrame");

                if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    // Restore the saved session state only when appropriate
                    try
                    {
                        await SuspensionManager.RestoreAsync();
                    }
                    catch (SuspensionManagerException)
                    {
                        //Something went wrong restoring state.
                        //Assume there is no state and continue
                    }
                }

                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
            }
            if (rootFrame.Content == null)
            {
                // When the navigation stack isn't restored navigate to the first page,
                // configuring the new page by passing required information as a navigation
                // parameter
                if (!rootFrame.Navigate(typeof(GroupedItemsPage), "AllGroups"))
                {
                    throw new Exception("Failed to create initial page");
                }
            }

            // Initialize Enduro if needed
            if (Instance == null)
            {
                bool success = await InitializeEnduroAsync();
                if (!success)
                {
                    // Enduro initialization failed, look in EnduroException for more information
                }
                else
                {
                    await DefineEnduroObjectStore();
                }            
            }

            CurrentUser = await QueryEnduroObjectStore("support@orandolabs.com");
            Prefs = CurrentUser.Prefs;
            string email = CurrentUser.Email;
            DateTime birthday = Prefs.Birthday;
            // Ensure the current window is active
            Window.Current.Activate();
        }

        /// <summary>
        /// Invoked when application execution is being suspended.  Application state is saved
        /// without knowing whether the application will be terminated or resumed with the contents
        /// of memory still intact.
        /// </summary>
        /// <param name="sender">The source of the suspend request.</param>
        /// <param name="e">Details about the suspend request.</param>
        private async void OnSuspending(object sender, SuspendingEventArgs e)
        {
            var deferral = e.SuspendingOperation.GetDeferral();
            await SuspensionManager.SaveAsync();
            await TerminateEnduroAsync();
            deferral.Complete();
        }
    }
}
